package com.liwei.controller;

import com.liwei.beans.Stu;
import com.liwei.dto.ResultDTO;
import com.liwei.validation.StuValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Locale;

@RestController
@RequestMapping("/")
public class IndexController {
    @Autowired
    MessageSource messageSource;
    //http://localhost:8080/get.action?id=10&name=lw&score=10.0
    @RequestMapping("get.action")
    public ResultDTO get(Stu stu, BindingResult bindingResult){
        StuValidation stuValidation = new StuValidation();
        stuValidation.validate(stu,bindingResult);
        /*if (bindingResult.hasErrors()){
            System.out.println("字段名：" + bindingResult.getFieldError().getField());
            System.out.println("错误code：" + bindingResult.getFieldError().getCode());
            System.out.println("错误RejectedValue：" + bindingResult.getFieldError().getRejectedValue());
            System.out.println("错误DefaultMessage：" +bindingResult.getFieldError().getDefaultMessage());
            String code=bindingResult.getFieldError().getCode();
            String message=messageSource.getMessage(code,null, Locale.getDefault());
            System.out.println("外部自定义的message：" +message);
        }*/
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors=bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("字段名：" + fieldError.getField());
                System.out.println("错误code：" + fieldError.getCode());
                System.out.println("错误RejectedValue：" + fieldError.getRejectedValue());
                System.out.println("错误DefaultMessage：" +fieldError.getDefaultMessage());
                String code=fieldError.getCode();
                String message=messageSource.getMessage(code,null, Locale.getDefault());
                System.out.println("外部自定义的message：" +message);
            }
        }
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setResult(resultDTO.SUCCESS);
        resultDTO.setData(stu);
        return resultDTO;
    }
}
